requirejs(['jquery', 'pageJs','config', 'arttemplateUtil','common','validform','wdatePicker','calendarpicker2','bootstrap_typeahead'], function($, pageJs,config, arttemplateUtil,common) {
	var param = {order_tab:1}
	var initData = function(){
		$.each($('#serchForm').serializeArray(), function(i, item) {
			if(item.value==""){
					delete param[item.name]
				}else{
					param[item.name]=item.value;
				}
		});
		changeDeliveryText();
		common.loading("执行中");
		common.common_ajax_request('/api/seller/v1/deliverList',param,true,function(data,code,msg){
			if(msg.businessCode==0){
				setData(data);
				pageJs.setPage(data.pageNo,data.totalPage,data.totalCount,callback);
			}else{
				setData({});
				window.layer.msg("系统异常");
			}
			layer.closeAll('loading'); //关闭加载层
		},"","post");
	}
	
	//切换页签查询时间文本
	var changeDeliveryText = function(){
		//根据选项卡调整按钮
		if(param.order_tab==2){
			$("#deliver_text").show();
			$('.querybtn .plBtn').hide();
			$('.querybtn .dataRefreshBtn').hide();
		}else{
			$("#deliver_text").hide();
			$("#deliver_time").val("");
			$('.querybtn .plBtn').show();
			$('.querybtn .dataRefreshBtn').show();
			
		}
	}
	
	var deliverlist_tpl;//订单列表模板
	var deliver_addr_tpl;//地址模板
	var deliverlist_much_tpl;//小区批量发货模板
	var deliver_fhyg_tpl;//订单预估
	
	var initTpl = function(){
		deliverlist_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliverlist_tpl.html'));
		deliver_addr_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_addr_tpl.html'));
		deliverlist_much_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliverlist_much_tpl.html'));
		deliver_fhyg_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_fhyg_tpl.html'));
	}
	
	//订单列表
	var setData = function(data){
		var res = {
				order_tab:param.order_tab,
				records:data.records,
				url:config.imgRoot()
		}
		$("#orderlist").html(deliverlist_tpl(res));
	}
	
	var callback = function(page){
		param.pageNo=page
		initData();
	}
	
	var init = function() {
		initTpl();
		initData();
		autoComplete();
	};
	var validserchform = $("#serchForm").Validform({
		tiptype:4,
		postonce:true,
		isShowRight:false
	});
	//页签选择
	$('#tabs-632335 a').click(function (e) {
		  param.order_tab=$(this).attr("tab_value");
		  param.pageNo=1;
		  changeDeliveryText();
		  initData();
	});
	
  //查询
  $('.serchBtn').on('click',function(){
	  if(validserchform.check()){
		  param.pageNo=1;
		  initData();
	  }
	});
  
	//重置
	$('.resetBtn').on('click',function(){
		$.each($('#serchForm').serializeArray(), function(i, item) {
			delete param[item.name];
		});
		$("#serchForm select[name=goods_type]").val("");
		$("form[name=serchForm] input").val("");
		$("#serchForm input").removeClass("Validform_error");
		$("#serchForm .Validform_checktip").removeClass("Validform_wrong").html("");
		initData();
	});
	
	//导出
	$('.excelBtn').on('click',function(){
		common.common_ajax_request('/api/seller/v1/exportDeliverBefore',{},false,function(data2,code,msg){
			if(msg.businessCode==0){
				$("#excel").attr("action",config.apiRoot()+"/api/seller/v1/exportDeliverList");
				var html = [];
				html.push("<input name=\"order_tab\" type='hidden' id=\"order_tab\" value=\""+param.order_tab+"\" />");
				$.each($('#serchForm').serializeArray(), function(i, item) {
					html.push("<input name=\""+item.name+"\" type='hidden' id=\""+item.name+"\" value=\""+item.value+"\" />");
				});
				$.each(config.setFullParameterArr({}), function(i, item) {
					html.push("<input name=\""+i+"\" type='hidden' id="+i+" value=\""+item+"\" />");
				});
				$("#excel").html(html.join(""));
				$("#excel").submit();
			}else{
				window.layer.msg(msg.businessNote);
			}
		},"","post");

	});
	
	//发货确定页
	$(document).off('click','.deliverBtn').on('click','.deliverBtn',function(){
		var id = $(this).attr("data-order-id");//订单id
		var detail_id = $(this).attr("data-detail-id");//子订单ID
		var goods_name = $(this).attr("data-goods-name");//子订单ID
		var goods_num = $(this).attr("data-goods-num");//子订单ID
		var goods_type = $(this).attr("data-goods-type");//子订单ID
		$('#addressModal').modal('show');
		common.common_ajax_request('/api/seller/v1/quyerOrderAddr',{order_id:id},false,function(data,code,msg){
			if(msg.businessCode==0){
				$('#addressModal').modal('show');
				var res = {
						data:data,
						of_id:id,
						detail_id:detail_id,
						goods_name:goods_name,
						goods_num:goods_num,
						goods_type:goods_type
				}
				$("#deliver_add_tpl").html(deliver_addr_tpl(res));
			}else{
				window.layer.msg(msg.businessNote);
			}
		});
		
	});
	
	//确认发货
	$(document).off('click','.deliverComfigBtn').on('click','.deliverComfigBtn',function(){
		$(this).attr("disabled","disabled");
		var id = $("#of_id").val();
		var detail_id = $("#detail_id").val();
		common.common_ajax_request('/api/seller/v1/deliverOrder',{order_id:id,detail_id:detail_id},false,function(data,code,msg){
			window.layer.msg(msg.businessNote);
			if(msg.businessCode==0){
				$('#addressModal').modal('hide');
				initData();
			}
		},"","get",function(){
			$(".deliverComfigBtn").removeAttr("disabled");
		});
		
	});
	//取消发货
	$(document).off('click','.cancelDeliverBtn').on('click','.cancelDeliverBtn',function(){
		var id = $(this).attr("data-order-id");
		var deliver_time = $(this).attr("data-detail-date");
		layer.confirm('确定要取消此次发货？', {
			  btn: ['确定','取消'] //按钮
			}, function(){
				common.common_ajax_request('/api/seller/v1/cancelDeliverOrder',{order_id:id,deliver_time:deliver_time.split(" ")[0]},false,function(data,code,msg){
					window.layer.msg(msg.businessNote);
					if(msg.businessCode==0){
						initData();
					}
				},"","get");
			}, function(){
			  
			});
	});
	//小区批量发货页
	$(document).off('click','.muchBtn').on('click','.muchBtn',function(){
		var area_ids = [];
		var area_order_count = 0;
		common.common_ajax_request('/api/seller/v1/quyerAreaCount',{},false,function(data,code,msg){
			if(msg.businessCode==0){
				$('#addressModal').modal('show');
				$("#deliver_add_tpl").html(deliverlist_much_tpl(data));
				//小区点击选
				$(document).off('click','.communityCount').on('click','.communityCount',function(){
					if(area_ids.indexOf($(this).attr("data-id")) > -1){
						area_ids.remove($(this).attr("data-id"));
						area_order_count=area_order_count-$(this).attr("data-count");
					}else{
						area_ids.push($(this).attr("data-id"));
						area_order_count=area_order_count+parseInt($(this).attr("data-count"));
					}
					$("#community_num").html(area_ids.length);
					$("#order_num").html(area_order_count);
				});
				//全选
				$(document).off('click','.chkall_community').on('click','.chkall_community',function(){
					if($("#chkall_community").is(':checked')==true){
						area_ids = [];
						area_order_count = 0;
						$(data.communityList).each(function(index,item){ 
							area_order_count=area_order_count+parseInt(item.community_count);
							area_ids.push(item.community_id);
						});
					}else{
						area_ids = [];
						area_order_count = 0;
					}
					$("#community_num").html(area_ids.length);
					$("#order_num").html(area_order_count);
				});
				$(document).off('click','.community_search').on('click','.community_search',function(){
					
					common.common_ajax_request('/api/seller/v1/quyerAreaCount',{community_name:$("#search_info").val()},false,function(data2,code,msg){
						if(msg.businessCode==0){
							area_ids = [];
							area_order_count = 0;
							var all_num = 0;
							var html = [];
							data = data2;
							$(data.communityList).each(function(index,item){ 
								html.push("<li data-count="+item.community_count+" data-id="+item.community_id+" class=\"communityCount\">"+item.community_name+" "+item.community_count+"</li>")
								all_num = all_num+parseInt(item.community_count);
							});
							$("#all_num").html(all_num);
							$("#community_ul").html(html.join(""));
							$("#community_num").html(area_ids.length);
							$("#order_num").html(area_order_count);
						}
					},"","post");
				});
				

			}else{
				window.layer.msg(msg.businessNote);
			}
		});
		
		$(document).off('click','.communitySubmit').on('click','.communitySubmit',function(){
			
			if(area_ids.length==0){
				window.layer.msg("请选择发货小区");
				return;
			}else{
				$(this).attr("disabled","disabled");
				common.common_ajax_request('/api/seller/v1/batchDeliver',{ids:area_ids.join(",")},false,function(data2,code,msg){
					window.layer.msg(msg.businessNote);
					if(msg.businessCode==0){
						$('#addressModal').modal('hide');
						initData();
					}
				},"","post",function(){
					$(".communitySubmit").removeAttr("disabled");
				});
			}
			
		});
		
	});
	//数据刷新
	$(document).off('click','.dataRefreshBtn').on('click','.dataRefreshBtn',function(){
		$(this).attr("disabled","disabled");
		common.common_ajax_request('/api/seller/v1/exportDeliverStatistics',{},false,function(data2,code,msg){
			window.layer.msg(msg.businessNote);
		},"","post",function(){
			$(".dataRefreshBtn").removeAttr("disabled");
		});
	});
	
	$(document).off('click','.houselist ul li').on('click','.houselist ul li',function(){
		$(this).toggleClass("on");
		var len1=$('.houselist ul li').length;
		var len2=$('.houselist ul').find(".on").length;
		if(len1==len2){
			$(".chkallhouse").prop('checked',true);
		}
		else{
			$(".chkallhouse").prop('checked',false);
		}
	});
	
	$(document).off('click','.chkallhouse').on('click','.chkallhouse',function(){
		if($(this).prop('checked')==true){
			$(".houselist ul li").addClass("on");
		}
		else{
			$(".houselist ul li").removeClass("on");
		}
	});

	//根据查询结果批量发货
	$(document).off('click','.querybtn .plBtn').on('click','.querybtn .plBtn',function(){
		window.layer.confirm('确认对搜索结果进行批量发货!',{btn:['确认','取消']},function(index, layero){
			layer.close(index);
			common.ajax_request2('post','/api/seller/v1/queryBatchDeliver?order_tab=1',$('#serchForm').serializeArray(),function($data,$code){
				if($code==200){
					initData();
				}
			});
		});
	});
	//发货订单数预估查询按钮
	$(document).off('click','.fhygBtn').on('click','.fhygBtn',function(){
		$('#fhygModal').modal('show');
		$("#fhygModal .modal-dialog .popfrm3").empty();
		//发货订单数预估日历控件
        $("#fhygModal .modal-dialog .popfrm3").calendarpicker2({
	            countTpl:"配送 {{delivery_count}} 单",
	        	clickUpdateValue:function($this){
	        		//判断是否是启动的日期
	        		if($this.hasClass('deliverStart')){
	        			//日历点击后调用该方法
	        			var time=new Date(($this.attr('data-date')-0));
	        			$('#fhygModal2 .modal-title').html(time.getFullYear() +'/'+(time.getMonth() + 1)+'/'+time.getDate());
	        			$('#fhygModal2').modal('show');
	        			
	        			//点击日志查询
	        			var quyerAreaCount=function(frmobj){
	        				frmobj.deliver_date=$this.attr('data-date');
							common.ajax_request2('post','/api/seller/v1/quyerAreaCount',frmobj,function($data,$code){
								if($code==200){
									$('#fhygModal2 .modal-dialog .qaccount').html('该商品预估量：'+$data.count+'单');
									$("#fhygModal2 .modal-dialog ul.community_ul").html(deliver_fhyg_tpl($data));
								}
							});
	        			};
	        			
	        			//商品查询
						common.ajax_request2('post','/api/seller/v1/quyerGoodsCount',{deliver_date:$this.attr('data-date')},function($data,$code){
							if($code==200){
								var _goods=$('#fhygModal2 select[name=goodsid]');
								_goods.empty();
		        				_goods.append('<option value="">全部</option>');
			        			$.each($data,function(_index,_data){
			        				_goods.append('<option value="'+_data.goods_id+'">'+_data.goods_name+'</option>');
			        			});
							}
							quyerAreaCount({});
						});
	        			
						// 小区查询按钮点击事件
	        			$(document).off('click','#fhygModal2 .qacbtn').on('click','#fhygModal2 .qacbtn',function(){
	        				quyerAreaCount({
	        					goods_id:$('#fhygModal2 select[name=goodsid]').val(),
	        					community_name:$('#fhygModal2 input[name=search_info]').val()
	        					});
	        			});
	        			
	        			//下拉搜索选中事件
	        			$(document).off('change','#fhygModal2 .qacselect').on('change','#fhygModal2 .qacselect',function(){
	        				quyerAreaCount({
	        					goods_id:$('#fhygModal2 select[name=goodsid]').val(),
	        					community_name:$('#fhygModal2 input[name=search_info]').val()
	        					});
	        			});
	        		}
	        	},
	        	updateCurrentMonthYear:function($p){
	        		common.loading("执行中");
	        		//根据时间查询
					common.ajax_request2('post','/api/seller/v1/deliverEstimates',{year:$p.currentYear,month:$p.currentMonth},function($data,$code){
						if($code==200){
			        		$p.calendarDataConversion($data);
			        		$p.updateValue();
						}
						layer.closeAll('loading'); //关闭加载层
					});
	        	}
		});
	});
	//搜索自动补全;给搜索框注册自动联想完成事件
	var autoComplete = function(){
			jQuery('#goods_name').typeahead({
				source: function (query, process) {
					//query是输入值
					if(query !== 'undefined' && typeof query != 'undefined' && query !==""){
						common.ajax_request2('post','/api/seller/v1/queryGoodsListByGoodsName', { "goods_name": query,goods_label:$("#goods_type").val()}, function ($data,$code) {
							if($code==200){
								process($data);
							}
							
						});
					}else{
						process({});
					}
				},
				matcher:function(item){
					return true;
				},
				updater: function (item) {
					return item; //这里一定要return，否则选中不显示
				},
				afterSelect: function (item) {
					//选择项之后的时间，item是当前选中的项
					//alert(item);
				},
				items: 10, //显示8条
				delay: 500 //延迟时间
			});
	};
	init();
});
